package com.xu.sso.client.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xu.sso.client.api.config.ApiConfig;
import com.xu.sso.client.api.model.OpenUserInfo;
import com.xu.sso.client.api.model.OpenUserRole;
import com.xu.sso.client.api.model.request.ApiRequest;
import com.xu.sso.client.api.model.response.ApiResponse;
import com.xu.sso.client.api.service.OpenApiService;
import com.xu.sso.client.api.utils.HttpUtil;
import com.xu.sso.client.api.utils.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("OpenApiService")
public class OpenApiServiceImpl implements OpenApiService {

    private Logger log = LoggerFactory.getLogger(OpenApiServiceImpl.class);

    @Value("${com.jufan.security.key}")
    private String key;
    @Value("${com.jufan.security.app_id}")
    private String appId;
    @Value("${com.jufan.security.service.path}")
    private String ssoUrl;

    @Override
    public List<OpenUserInfo> findAllUser() {
        ApiRequest request = convert(null, ApiConfig.FIND_ALL_USERS);
        String result = HttpUtil.postJson(ssoUrl + ApiConfig.API, JSONObject.toJSONString(request));
        if (null != result && result.trim().length() > 0) {
            try {
                ApiResponse response = JSONObject.parseObject(result, ApiResponse.class);
                boolean check = SignUtil.verifySign(response, request, key);
                if (!check) {
                    log.error(">>>>>>>>>>>>>OpenApi findAllUser check sign error...");
                    return null;
                }
                if (!"Success".equals(response.getCode())) {
                    log.error(">>>>>>>>>>>>>OpenApi findAllUser error code==={}...msg==={}", response.getCode(), response.getMsg());
                    return null;
                }
                if (null != response.getContent() && response.getContent().trim().length() > 0) {
                    return JSONObject.parseArray(response.getContent(), OpenUserInfo.class);
                }
            } catch (Exception e) {
                log.error(">>>>>>>>>>>>>>>>OpenApi findAllUser error response==={}", result);
            }
        }
        return null;
    }

    @Override
    public List<OpenUserInfo> findUserInList(List<String> usernames) {
        ApiRequest request = convert(JSONObject.toJSONString(usernames), ApiConfig.FIND_USERS_IN_LIST);
        String result = HttpUtil.postJson(ssoUrl + ApiConfig.API, JSONObject.toJSONString(request));
        if (null != result && result.trim().length() > 0) {
            try {
                ApiResponse response = JSONObject.parseObject(result, ApiResponse.class);
                boolean check = SignUtil.verifySign(response, request, key);
                if (!check) {
                    log.error(">>>>>>>>>>>>>OpenApi findUserInList check sign error...");
                    return null;
                }
                if (!"Success".equals(response.getCode())) {
                    log.error(">>>>>>>>>>>>>OpenApi findUserInList error code==={}...msg==={}", response.getCode(), response.getMsg());
                    return null;
                }
                if (null != response.getContent() && response.getContent().trim().length() > 0) {
                    return JSONObject.parseArray(response.getContent(), OpenUserInfo.class);
                }
            } catch (Exception e) {
                log.error(">>>>>>>>>>>>>>>>OpenApi findUserInList error response==={}", result);
            }
        }
        return null;
    }

    @Override
    public List<OpenUserInfo> findUserByLikeName(String username) {
        ApiRequest request = convert(username, ApiConfig.FIND_USERS_BY_LIKE);
        String result = HttpUtil.postJson(ssoUrl + ApiConfig.API, JSONObject.toJSONString(request));
        if (null != result && result.trim().length() > 0) {
            try {
                ApiResponse response = JSONObject.parseObject(result, ApiResponse.class);
                boolean check = SignUtil.verifySign(response, request, key);
                if (!check) {
                    log.error(">>>>>>>>>>>>>OpenApi findUserByLikeName check sign error...");
                    return null;
                }
                if (!"Success".equals(response.getCode())) {
                    log.error(">>>>>>>>>>>>>OpenApi findUserByLikeName error code==={}...msg==={}", response.getCode(), response.getMsg());
                    return null;
                }
                if (null != response.getContent() && response.getContent().trim().length() > 0) {
                    return JSONObject.parseArray(response.getContent(), OpenUserInfo.class);
                }
            } catch (Exception e) {
                log.error(">>>>>>>>>>>>>>>>OpenApi findUserByLikeName error response==={}", result);
            }
        }
        return null;
    }

    @Override
    public OpenUserInfo findUserByName(String username) {
        ApiRequest request = convert(username, ApiConfig.FIND_USERS_BY_USERNAME);
        String result = HttpUtil.postJson(ssoUrl + ApiConfig.API, JSONObject.toJSONString(request));
        if (null != result && result.trim().length() > 0) {
            try {
                ApiResponse response = JSONObject.parseObject(result, ApiResponse.class);
                boolean check = SignUtil.verifySign(response, request, key);
                if (!check) {
                    log.error(">>>>>>>>>>>>>OpenApi findUserByName check sign error...");
                    return null;
                }
                if (!"Success".equals(response.getCode())) {
                    log.error(">>>>>>>>>>>>>OpenApi findUserByName error code==={}...msg==={}", response.getCode(), response.getMsg());
                    return null;
                }
                if (null != response.getContent() && response.getContent().trim().length() > 0) {
                    return JSONObject.parseObject(response.getContent(), OpenUserInfo.class);
                }
            } catch (Exception e) {
                log.error(">>>>>>>>>>>>>>>>OpenApi findUserByName error response==={}", result);
            }
        }
        return null;
    }

    @Override
    public List<OpenUserRole> findUserRoles(String username) {
        ApiRequest request = convert(username, ApiConfig.FIND_USER_ROLES);
        String result = HttpUtil.postJson(ssoUrl + ApiConfig.API, JSONObject.toJSONString(request));
        if (null != result && result.trim().length() > 0) {
            try {
                ApiResponse response = JSONObject.parseObject(result, ApiResponse.class);
                boolean check = SignUtil.verifySign(response, request, key);
                if (!check) {
                    log.error(">>>>>>>>>>>>>OpenApi findUserRoles check sign error...");
                    return null;
                }
                if (!"Success".equals(response.getCode())) {
                    log.error(">>>>>>>>>>>>>OpenApi findUserRoles error code==={}...msg==={}", response.getCode(), response.getMsg());
                    return null;
                }
                if (null != response.getContent() && response.getContent().trim().length() > 0) {
                    return JSONObject.parseArray(response.getContent(), OpenUserRole.class);
                }
            } catch (Exception e) {
                log.error(">>>>>>>>>>>>>>>>OpenApi findUserRoles error response==={}", result);
            }
        }
        return null;
    }

    private ApiRequest convert(String content, String method) {
        ApiRequest request = new ApiRequest();
        request.setAppId(appId);
        request.setContent(content);
        request.setMethod(method);
        return SignUtil.sign(request, key);
    }

}
